package cn.hetra.hj212.client;

import cn.hetra.hj212.core.HJ212Data;
import org.springframework.util.Assert;

import java.util.concurrent.ExecutionException;

public class HJ212ClientSession implements TcpConnectionHandler {

    private volatile TcpConnection connection;

    public boolean isConnected() {
        return (this.connection != null);
    }

    /**
     * 每次重连都会回调
     * @param connection the connection
     */
    @Override
    public void afterConnected(TcpConnection connection) {
        this.connection = connection;
    }

    public void send(HJ212Data message) {
        TcpConnection conn = this.connection;
        Assert.state(conn != null, "Connection closed");
        try {
            conn.send(message).get();
        } catch (ExecutionException ex) {
            throw new IllegalStateException(ex);
        } catch (Throwable ex) {
            throw new IllegalStateException(ex);
        }
    }

    @Override
    public void afterConnectFailure(Throwable ex) {

    }

    @Override
    public void handleMessage(HJ212Data message) {
        System.out.println(message.getData());
    }

    @Override
    public void handleFailure(Throwable ex) {

    }

    @Override
    public void afterConnectionClosed() {
        resetConnection();
    }

    private void resetConnection() {
        TcpConnection conn = this.connection;
        this.connection = null;
        if (conn != null) {
            try {
                conn.close();
            } catch (Throwable ex) {
                // ignore
            }
        }
    }
}
